package com.android.lovely.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.format.DateUtils
import android.text.style.AbsoluteSizeSpan
import android.view.ViewGroup
import androidx.core.graphics.toColorInt
import androidx.core.text.buildSpannedString
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.lovely.R
import com.android.lovely.aav.PreferentialManager
import com.android.lovely.aav.PreferentialManager.playEnter
import com.android.lovely.admob.Ad
import com.android.lovely.admob.AdmobManager
import com.android.lovely.admob.showReword
import com.android.lovely.api.getRewardGemUseCase
import com.android.lovely.data.PayDetail
import com.android.lovely.databinding.ActivityPayBinding
import com.android.lovely.databinding.ItemPayAdBinding
import com.android.lovely.databinding.ItemPayBinding
import com.android.lovely.databinding.ItemPayFirstBinding
import com.android.lovely.databinding.ItemPayProductBinding
import com.android.lovely.databinding.ItemPayTitleBinding
import com.android.lovely.ext.fullScreen
import com.android.lovely.ext.windowBackgroundNav
import com.android.lovely.ext.windowBackgroundStatus
import com.android.lovely.framework.BaseAdapter
import com.android.lovely.framework.BaseMvvmActivity
import com.android.lovely.framework.UIController
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.manager.KVStore
import com.android.lovely.manager.WorkStore
import com.android.lovely.ui.dialog.PreferentialDialog
import com.android.lovely.ui.fragment.HomeListItemDecoration
import com.android.lovely.ui.viewmodel.PayViewModel
import com.android.lovely.user.UserManager
import com.android.lovely.user.UserManager.registerAuthChange
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.inflater.LayoutInflaterExt.layoutInflater
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.withTimeoutOrNull

/**
 *
 * @author why
 * @date 2025/3/25 18:11
 */
class PayActivity : BaseMvvmActivity<ActivityPayBinding, PayViewModel>() {
    private val concatAdapter =
        ConcatAdapter(ConcatAdapter.Config.Builder().setIsolateViewTypes(false).build())

    private val titleAdapter by lazy {
        PayTitleAdapter()
    }
    private val firstAdapter by lazy {
        PayFirstAdapter()
    }

    private val productListAdapter by lazy {
        ProductListAdapter()
    }


    override fun initView(savedInstanceState: Bundle?) {
        mBinding.llTop.addStatusBarMarginTop()
        mBinding.ivLeft.clickable {
            finish()
        }
        mBinding.tvDetail.clickable {
            startPage<TansListActivity>()
        }
        mBinding.report.clickable {
            startPage<RechargeBackActivity>()
        }
        titleAdapter.onRefresh = {
            lifecycleScope.launchWithLoading {
                UserManager.refreshAuthSync()
            }
        }
        lifecycleScope.launchSafety {
            PreferentialManager.eventFlow.collectLatest {
                mBinding.preferential.isVisible = UserManager.isB()
                mBinding.preferential.playEnter()
            }
        }
        mBinding.edgeLayout.clickable {
            PreferentialDialog().show(supportFragmentManager)
        }
        firstAdapter.onPay = {
            viewModel.pay(this, it)
        }
        productListAdapter.onPay = {
            viewModel.pay(this, it)
        }

        mBinding.rv.layoutManager = LinearLayoutManager(this)
        mBinding.rv.adapter = concatAdapter

        concatAdapter.addAdapter(titleAdapter)
        concatAdapter.addAdapter(firstAdapter)
        concatAdapter.addAdapter(productListAdapter)
        UserManager.refreshAuth()
        registerAuthChange {
            titleAdapter.updateList(arrayListOf(it.point.toString()))
            mBinding.tvDetail.isVisible = UserManager.isB()
        }
        if (Ad.WalletPage.getId().isNotEmpty()) {
            mBinding.layoutFree.isVisible = true
            setAdLayout()
        }
        mBinding.get.clickable {
            showPayAd()
        }
        if (!DateUtils.isToday(KVStore.discountShowTime) && UserManager.isB() && PreferentialManager.isEnable) {
            PreferentialDialog().show(supportFragmentManager)
        }
        lifecycleScope.launchSafety {
            viewModel.productFlow.collect {
                productListAdapter.updateList(arrayListOf(it.list))
                if (it.firstPay != null) {
                    firstAdapter.updateList(arrayListOf(it.firstPay))
                } else {
                    firstAdapter.updateList(arrayListOf())
                }
            }
        }
        viewModel.requestProductList()
    }

    private fun setAdLayout() {
        val max = UserManager.userInfo?.adBuyPageMaxNum ?: 0
        mBinding.get.text = getString(R.string.get_count, WorkStore.getInstance().buyPageShowCount, max)
        mBinding.disable.isVisible = Ad.WalletPage.enable().not()
    }

    private fun showPayAd() {
        lifecycleScope.launchWithLoading {
            withTimeoutOrNull(15000) {
                Ad.WalletPage.load()?.join()
            }
            showReword(Ad.WalletPage) {
                if (it) {
                    lifecycleScope.launchWithLoading {
                        getRewardGemUseCase("ad_in_buy_page").let {
                            UserManager.updateGems(it.getOrDefault("surplus", UserManager.userInfo?.point ?: 0))
                            showToast(getString(R.string.sign_success, (it.getOrDefault("point", 0)).toString()))
                        }
                        WorkStore.getInstance().buyPageShowCount++
                        setAdLayout()
                    }.onError {
                        showToast(getString(R.string.ad_fail))
                    }
                } else {
                    showToast(getString(R.string.ad_fail))
                }
            }
        }
    }

}

class PayTitleAdapter : BaseAdapter<String, ItemPayTitleBinding>() {
    var onRefresh: (() -> Unit)? = null


    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: String?,
        binding: ItemPayTitleBinding,
        position: Int
    ) {
        binding.count.text = item ?: "0"
        binding.tvTitle.clickable {
            onRefresh?.invoke()
        }
    }

    override fun getItemViewType(position: Int): Int {
        return 100
    }
}

class PayFirstAdapter : BaseAdapter<PayDetail, ItemPayFirstBinding>() {
    var onPay: ((PayDetail) -> Unit)? = null
    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: PayDetail?,
        binding: ItemPayFirstBinding,
        position: Int
    ) {
        item ?: return
        binding.apply {
            root.context.resources.getString(
                R.string.pay_off,
                "${(((item.oldPrice - item.price) / item.oldPrice) * 100).toInt()}%"
            ).also {
                tvDiscount.text = it
            }
            tvGems.text = root.context.getString(R.string.first_pay_title, item?.point ?: "")
            tvCount.text = root.context.getString(R.string.first_pay_money, item?.price.toString())
            tvOld.text = root.context.getString(R.string.first_pay_money, item?.oldPrice.toString())
            // 设置中划线
            tvOld.paintFlags = tvOld.paintFlags or android.graphics.Paint.STRIKE_THRU_TEXT_FLAG
            // 去除锯齿，让中划线更平滑
            tvOld.paint.isAntiAlias = true

            binding.buy.clickable {
                item?.let { it1 -> onPay?.invoke(it1) }
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return 101
    }
}

class ProductListAdapter : RecyclerView.Adapter<ProductListAdapter.ProductListViewHolder>() {
    var onPay: ((PayDetail) -> Unit)? = null

    protected val list = mutableListOf<List<PayDetail>>()


    val adapter by lazy {
        ProductItemListAdapter()
    }

    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ProductListViewHolder {
        return ProductListViewHolder(p0)
    }

    override fun onBindViewHolder(p0: ProductListViewHolder, p1: Int) {
        val item = getItemAt(p1) ?: return
        p0.binding.apply {
            adapter.onPay = onPay
            p0.recyclerView.adapter = adapter
            adapter.updateList(item)
        }
    }

    fun getItemAt(position: Int): List<PayDetail>? {
        if (position > list.size) {
            return null
        }
        return list[position]
    }

    override fun getItemViewType(position: Int): Int {
        return 102
    }

    override fun getItemCount(): Int {
        return list.size
    }

    open fun updateList(newList: ArrayList<List<PayDetail>>) {
        list.clear()
        list.addAll(newList)
        notifyDataSetChanged()
    }

    inner class ProductListViewHolder(
        parent: ViewGroup,
        val binding: ItemPayProductBinding = ItemPayProductBinding.inflate(
            parent.layoutInflater,
            parent,
            false
        )
    ) : RecyclerView.ViewHolder(binding.root) {
        val recyclerView: RecyclerView = binding.rvPay.apply {
            layoutManager = GridLayoutManager(binding.root.context, 2)
            addItemDecoration(HomeListItemDecoration(10.dp))
        }
    }


}

class ProductItemListAdapter : BaseAdapter<PayDetail, ItemPayBinding>() {
    var onPay: ((PayDetail) -> Unit)? = null
    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: PayDetail?,
        binding: ItemPayBinding,
        position: Int
    ) {
        item ?: return
        binding.apply {
            tvCount.text = root.context.getString(R.string.first_pay_title, item?.point ?: "")
            count.text = root.context.getString(R.string.first_pay_money, item?.price.toString())
            tvOld.text = root.context.getString(R.string.first_pay_money, item?.oldPrice.toString())
            tvOld.paint.isStrikeThruText = true
            if (item.oldPrice > 0) {
                val spannedDayText = buildSpannedString {
                    val dayText = "${(((item.oldPrice - item.price) / item.oldPrice) * 100).toInt()}%"
                    // 先添加字体大小为 20 的部分
                    append(dayText)
                    setSpan(
                        AbsoluteSizeSpan(17, true),
                        0,
                        dayText.length,
                        SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    // 再添加一个空格
                    append(" ")
                    // 接着添加字体大小为 26 的部分
                    val extraText = root.context.resources.getString(
                        R.string.off,
                    )
                    val start = length
                    append(extraText)
                    setSpan(
                        AbsoluteSizeSpan(10, true),
                        start,
                        start + extraText.length,
                        SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
                tvReduction.text = spannedDayText
                tvReduction.isVisible = true
                tvOld.isVisible = true
            } else {
                tvReduction.isVisible = false
                tvOld.isVisible = false
            }

            binding.buy.clickable {
                item?.let { it1 -> onPay?.invoke(it1) }
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return 103
    }

}

class PayAdAdapter : BaseAdapter<String, ItemPayAdBinding>() {
    //    var onPay: ((PayDetail) -> Unit)? = null
    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: String?,
        binding: ItemPayAdBinding,
        position: Int
    ) {

    }

    override fun getItemViewType(position: Int): Int {
        return 104
    }
}